import { defineStore } from 'pinia';
import {getMenuListApi} from "@/api/menu";
import type {RouteRecordRaw} from "vue-router";
import Layout from '@/layout/index.vue';
import Center from '@/layout/center/center.vue'
const modules = import.meta.glob('../../views/**/*.vue')

export const menuStore = defineStore('menuStore', {
    state: () => {
        return {
            menuList:[
                {
                path: "/dashboard",
                name: "dashboard",
                component: "Layout",
                meta: { title: "首页", icon: 'HomeFIled',roles:['sys:dashboard'] }
                }
            ]
        }

    },
    getters: {
        getMenu(state){
            return state.menuList
        }

    },
    actions: {
        //获取动态菜单数据
        getMenuList(router:any,userId:string){
            return new Promise((resolve, reject)=>{
                getMenuListApi(userId).then((res)=>{
                    let accessRoute
                    if(res && res.code==200){
                        //生成路由
                        console.log(res.data)
                        accessRoute = generatorRouter(res.data,router) as any
                        this.menuList = this.menuList.concat(accessRoute)

                    }
                    resolve(this.menuList)
                }).catch((error)=>{
                    reject(error)
                })
            })
        }
    },

})
//生成动态路由
export function generatorRouter(routes:RouteRecordRaw[],router:any){
    const res:Array<RouteRecordRaw> = []
    routes.forEach((route:any)=>{
        const temp= {...route}
        const component = temp.component
        if(route.component){
            if(component=='layout'){
                temp.component = Layout
            }else{
                temp.component = modules[`../../${component}`]
            }
        }
        if(temp.children && temp.children.length>0){
            if(route.component!='layout'){
                temp.children = Center
            }
            temp.children = generatorRouter(temp.children,router)
        }
        res.push(temp)
        router.addRoute(temp)
    })
    return res;
}